<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container" >
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" >
        <el-form-item label="名称" prop="goodName">
          <el-input
            v-model="queryParams.goodName"
            placeholder="请输入名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="goodStatus">
          <el-select
            v-model="queryParams.goodStatus"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="2" />
          </el-select>
        </el-form-item>


        <el-form-item label="商品属性" prop="goodsTarget">
          <el-select
            v-model="queryParams.goodsTarget"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option label="普通商品" :value="1" />
            <el-option label="会员商品" :value="2" />
            <el-option label="福利商品" :value="3" />

          </el-select>
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button class="filter-item" type="primary" icon="search" @click="handleQuery">
            搜索
          </el-button>

          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>


        </el-form-item>
      </el-form>
    </div>


  <el-row :gutter="20" >
      <!-- 部门树 -->
      <el-col :lg="3" :xs="24" class="mb-[12px]" style="display: none;">
          商品分类:
        <el-tree
ref="deptTreeRef"
              style="border: 1px solid #ccc;margin-left: 0px; padding-left: 0px; width: 200px; margin-top: 10px; height:500px; overflow-y: scroll;"
              :data="deptList"
              :props="{ children: 'children', label: 'label', disabled: '' }"
              :expand-on-click-node="false"
              :filter-node-method="handleFilter"
              default-expand-all
              @node-click="handleNodeClick"
            />
      </el-col>

      <el-col :lg="24" :xs="24" class="mb-[12px]">
        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar">
            <div class="data-table__toolbar--actions">
              <el-button
                v-hasPerm="['goods:goods:add']"
                type="success"
                icon="plus"
                @click="handleOpenDialog({})"
              >
                新增
              </el-button>
              <el-button
              v-hasPerm="['goods:goods:delete']"
                style="display: none;"
                type="danger"
                :disabled="selectIds.length === 0"
                icon="delete"
                @click="handleDelete()"
              >
                删除
              </el-button>
            </div>
          </div>
          <el-table
            v-loading="loading" 
            :data="Lists"
            row-key="id"
            default-expand-all
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            class="data-table__content"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="id" label="ID" width="150" />
            <el-table-column prop="name" label="名称"  />

            <el-table-column prop="logo" label="图片" >
              <template #default="{ row }">
                <el-image
                  style="width: 50px; height: 50px; border-radius: 50%"
                  :src="'https://clip.xxauesa.com/'+row.image"
                  :preview-src-list="[row.image]"
                />
              </template>
            </el-table-column>

            <el-table-column prop="goodsType.name" label="分类名称"  />
            <el-table-column prop="price" label="销售价格"  />
            <el-table-column prop="status" label="状态" width="150">
              <template #default="scope">
                <div style="display: flex;">
                  <el-tag v-if="scope.row.status == 1" style="margin-top: 5px;margin-right: 5px;" type="success">上架</el-tag>
                  <el-tag v-else style="margin-top: 5px;margin-right: 5px;" type="info">下架</el-tag>
                  
                  <el-switch
                    v-model="scope.row.status"
                    :active-value="1"
                    :inactive-value="2"
                    @change="handleStatusChange(scope.row)"
                  ></el-switch>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="createTime" label="创建时间" width="220" />
            <el-table-column label="操作" fixed="right" align="left" width="200">
              <template #default="scope">
                <el-button
                  v-hasPerm="['goods:goods:edit']"
                  type="primary"
                  link
                  size="small"
                  icon="edit"
                  @click.stop="handleOpenDialog(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-hasPerm="['goods:goods:delete']"
                  type="danger"
                  link
                  size="small"
                  icon="delete"
                  @click.stop="handleDelete(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>

      </el-col>
    </el-row>

    <el-dialog
            v-if="loadings==true"

      v-model="dialog.visible"
      :title="dialog.title"
      width="1200px"
      @closed="handleCloseDialog"
    >
      <el-form ref="FormRef" :model="formData" :rules="rules" label-width="170px">
        
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="商品分类" prop="cate_id" required>
          <el-select v-model="formData.cate_id" placeholder="请选择商品分类">
            <el-option 
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="图片">
          <SingleImageUpload v-model="formData.logo" :data="{fileType:'image'}" />
        </el-form-item>

        <el-form-item label="多图上传">
          <MultiImageUpload v-if="loadings==true" v-model="formData.images" :title="dialog.title" :limit="20" :data="{fileType:'image'}" />
        </el-form-item>

        <!-- 使用自定义的上传组件 -->
        <!-- <el-form-item label="视频上传">
          <VideoUpload></VideoUpload> 
        </el-form-item> -->


        <!-- 多规格部分 -->
        <el-form-item label="商品规格">
          <div class="specification-section">
            <el-switch
              v-model="formData.hasMultipleSpecs"
              active-text="多规格"
              inactive-text="单规格"
            />
            
            <template v-if="formData.hasMultipleSpecs">
              <SpecificationEditor 
                :model-value = "formData.specifications"
                :current-skus = "formData.guige"
                @change="handleSpecChange"
                @change2="handleSpecChange2"
              />
            </template>
            <template v-else>
              <!-- 单规格价格和库存输入 -->
              <div class="single-spec">
                <el-form-item label="市场价格" prop="cost_price" >
                  <el-input v-model="formData.cost_price"  />
                </el-form-item>
                <el-form-item label="销售价格" prop="price" >
                  <el-input v-model="formData.price"  />
                </el-form-item>
                <el-form-item label="库存" prop="stock" >
                  <el-input-number v-model="formData.stock" :min="0" />
                </el-form-item>
              </div>
            </template>
          </div>
        </el-form-item>
        
        <el-form-item label="显示排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            style="width: 100px"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="状态" >
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否是福利商品" >
          <el-radio-group v-model="formData.isBenefit">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">不是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否是会员商品" >
          <el-radio-group v-model="formData.isMember">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">不是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否包邮" >
          <el-radio-group v-model="formData.isDelivery">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="虚拟销量" >
          <el-input-number v-model="formData.virtualSales"  :min="0"/>
        </el-form-item>

        <el-form-item label="福利商品限购数量" >
          <el-input-number v-model="formData.quotaNum"  :min="0"/>
        </el-form-item>

        <!-- <el-form-item label="视频ID" >
          <el-input-number v-model="formData.videoId"  :min="0"/>
        </el-form-item> -->

        <el-form-item label="视频ID" prop="formData.videoId">
          <el-select
            v-model="formData.videoId"
            placeholder="视频ID"
            clearable
            style="width: 150px"
          >
            <el-option v-for="(item,index) in video_list" :key="index" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>

        <WangEditor v-if="loadings==true" v-model="formData.content" height="200px" style="width: 80%;margin-left: 10%;" />

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "商品",
  inheritAttrs: false,
});

import GoodsAPI, { GoodsVO,GoodsForm } from "@/api/system/goods.api";
import SpecificationEditor from "./SpecificationEditor.vue";
// import VideoUpload from "./VideoUpload.vue";

const queryFormRef = ref();
const FormRef = ref();

const loading = ref(false);
const loadings = ref(false);

const selectIds = ref<number[]>([]);


const queryParams = reactive<any>({
  goodName: "",
  goodsTarget: "",
  goodStatus: "",
  classifyId: "",
  pageNum: 1,
  pageSize: 10,
});

const deptList = ref<OptionType[]>(); 
GoodsAPI.getCateTree().then((res) => {
  for(const item of res) {
    item.label = item.name; // 设置label属性
    item.value = item.id; // 设置value属性

    const children = item.children || [];
    for(const child of children) {  
      child.label = child.name; // 设置子节点的label属性
      child.value = child.id; // 设置子节点的value属性
      child.children = digui(child.children || []); // 递归处理子节点
    }
    item.children = children || []; // 确保children存在
  }
  
  deptList.value = res;
  console.log("部门树数据:", deptList.value);
});

function digui(children: any[]) {
  for(const child of children) {  
    child.label = child.name; // 设置子节点的label属性
    child.value = child.id; // 设置子节点的value属性
  }
  return children;
}



const deptTreeRef = ref(); 
const deptName = ref(); 


function handleFilter(value: string, data: any) {
  if (!value) {
    return true;
  }
  return data.label.indexOf(value) !== -1;
}

function handleNodeClick(data: { [key: string]: any }) {
  console.log("选中:", data.id);
  queryParams.classifyId = data.id;
  handleQuery()
}

watchEffect(
  () => {
    deptTreeRef.value.filter(deptName.value);
  },
  {
    flush: "post", // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

const dialog = reactive({
  title: "",
  visible: false,
});
const formData = reactive<GoodsForm>({
  /** ID(新增不填) */
  id: '',
  /** 名称 */
  name: '',
  /** logo */
  logo: '',
  /** content */
  content: '',
  /** images */
  images: [],
  /** 排序 */
  sort: 1,
  /** 状态(1:启用；0：禁用) */
  status: 1,
  /** 是否是福利商品 */
  isBenefit: 0,
  /** 是否是会员商品 */
  isMember: 0,
  /** 销售价格 */
  price: '0',
   /** 市场价格 */
  cost_price: '0',
  /** 库存 */
  stock: 0,
  /** 是否包邮 */
  isDelivery: 0,
  /** 虚拟销量 */
  virtualSales: 0,
  /** 福利商品限购数量 */
  quotaNum: 0,
  /** 视频ID */
  videoId: 0,
  /** 规格 */
  specifications:[],
  /** 规格内容 */
  guige: [],
  
  hasMultipleSpecs:false
});




const rules = reactive({
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  cate_id: [{ required: true, message: "商品分类不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
});

const Lists = ref<GoodsVO[]>();
const total = ref(0);

let editForm = {};


const categories = ref();

GoodsAPI.getCateList().then((res) => {
   categories.value = res
})

const video_list = ref();
GoodsAPI.getGoodsCateTree().then((res) => {
   video_list.value = res
   console.log("视频分类数据:", video_list.value);
})



interface ProductSpecification {
  name: string
  values: string[]
  skus?: SkuItem[]
}

export interface SkuItem {
  id?: string
  specs: { [key: string]: string }
  price: number
  stock: number
  code?: string
  image?: string
}

function handleStatusChange(row: GoodsVO) {
  const newStatus = row.status ;
  const data ={ dataId: row.id, setVal: newStatus,setType:2 }
  GoodsAPI.updateStatus(data)
    .then(() => {
      ElMessage.success("状态更新成功");
      handleQuery();
    })
    .catch((error) => {
      console.error("状态更新失败:", error);
      ElMessage.error("状态更新失败");
    });
}

// 查询
function handleQuery() {
  console.log(queryParams)
  loading.value = true;

  if(queryParams.goodStatus == undefined || queryParams.goodStatus == null){
    queryParams.goodStatus = ''
  }
  if(queryParams.goodsTarget == undefined || queryParams.goodsTarget == null){
    queryParams.goodsTarget = ''
  }


  GoodsAPI.getList(queryParams)
    .then((res) => {
      Lists.value = res.data;
      total.value = res.total;
    })
    .catch((error) => {
      console.error("查询商品列表失败:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}



// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

const escape2Html = (str: any) => {
  const arrEntities: { [key: string]: string } = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };
  return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all: string, t: string) {
    return arrEntities[t];
  });
}


/**
 * 打开新增弹窗
 *
 * @param Id ID
 */
function handleOpenDialog(row?:any) {
  if (row.id) {
    dialog.title = "修改";
    loadings.value = false
    GoodsAPI.info({dataId:row.id})
    .then((res) => {
      
      let isDelivery = 0
      if(res.deliveryDesc=='不包邮'){
        isDelivery = 0
      }else{
        isDelivery = 1
      }

      const banner = res.banner.split(',')
      const array =[]
      for(let i=0;i<banner.length;i++){
        array.push(banner[i])
      }
      
      let spec = <any>[]
      const guige2 = <any>[]
      let hasMultipleSpecs2 = false
      if(res.specType==2){
         hasMultipleSpecs2 = true
         spec = Object.entries(res.goodSpec).map(([name, values]) => ({
          name,
          values,
          skus: [], // 默认空数组
        }));


        const goodsItems = res.goodsItems
        for(let i=0;i<goodsItems.length;i++){
          const specValueStr = goodsItems[i]['specValueStr']
          const values = specValueStr.split(",");
          const result = <any>{};
          const obj = res.goodSpec
          Object.entries(obj).forEach(([key], index) => {
            result[key] = values[index];
          });
          guige2.push({
            cost_price:goodsItems[i]['costPrice'],
            image:goodsItems[i]['image'],
            price:goodsItems[i]['price'],
            specs:result,
            stock:goodsItems[i]['stock'],
            virtualSales:goodsItems[i]['virtualSales']
          })
        }
      }

      let content2 = res.content || '';
      content2 = content2.replace(/<[^>]+>/g, ''); // 移除所有HTML标签
      content2 = content2.replace(/&nbsp;/g, ''); // 移除所有空
      content2 = content2.replace(/&lt;/g, '<'); // 替换&lt;为<
      content2 = content2.replace(/&gt;/g, '>'); // 替换&gt;为> 
      content2 = escape2Html(content2); // 转义HTML实体

      editForm = {
        id:res.id,
        cate_id:res.typeId,
        name:res.name,
        logo:res.image,
        content:content2,
        sort:res.sort,
        status:res.status,
        isBenefit:res.isBenefit,
        isMember:res.memberType,
        price:res.price,
        cost_price:res.costPrice,
        stock:res.stock,
        isDelivery,
        virtualSales:res.virtualSales,
        hasMultipleSpecs:hasMultipleSpecs2,
        quotaNum:res.quotaNum,
        videoId:res.videoId,
        specifications:spec,
        guige:guige2
      }

      Object.assign(formData, editForm);

      formData.images = array
      dialog.visible = true;
      loadings.value = true
   
    })

  } else {
    dialog.title = "新增";
    loadings.value = false

    editForm = {
        id:'',
        cate_id:'',
        name:'',
        logo:'',
        content:'',
        sort:0,
        status:2,
        isBenefit:0,
        isMember:0,
        price:0,
        cost_price:0,
        stock:0,
        isDelivery:0,
        virtualSales:0,
        quotaNum:0,
        videoId:0,
        specifications:[],
        guige:[]
      }

      Object.assign(formData, editForm);

      formData.images = []
      dialog.visible = true;
      loadings.value = true
  }

  

}


const handleSpecChange = (specs: ProductSpecification[],type:number) => {
  console.log("规格变化:", specs, type);
  formData.specifications = specs
}

const handleSpecChange2 = (specs: SkuItem[],type:number) => {
  console.log("SKU变化:", specs, type);
  formData.guige = specs
}



const formJson = ref();


// 提交表单
function handleSubmit() {
  FormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const goods_arr = []
      const good_spec = <any>{}
      if(formData.hasMultipleSpecs){
        const goods_item = formData.guige
        for(let i = 0; i < goods_item.length; i++) {
          let specValStr2 = '';
          const arr = Object.values(goods_item[i].specs);
          if (arr.length > 0) {
            specValStr2 = arr.join(',');
          }
          goods_arr.push({
            id: i,
            specValStr: specValStr2,
            price: goods_item[i].price,
            stock: goods_item[i].stock,
            costPrice: goods_item[i].cost_price,
            image: goods_item[i].image,
            virtualSales: goods_item[i].virtualSales,
          })
        }
      
        const specification = formData.specifications
        for(let j = 0; j < specification.length; j++) {
          good_spec[specification[j].name] = specification[j].values
        }
      
      }
      
      formJson.value = {
        dataId: formData.id?formData.id:'',
        goodName: formData.name,
        goodImage: formData.logo,
        goodBanner: formData.images,
        goodStatus: formData.status,
        isBenefit: formData.isBenefit,
        isMember: formData.isMember,
        goodPrice: formData.price,
        costPrice: formData.cost_price,
        classId: formData.cate_id,
        goodContent: escape2Html(formData.content),
        specType: formData.hasMultipleSpecs ? 2 : 1,
        goodStock: formData.stock,
        isDelivery: formData.isDelivery,
        virtualSales: formData.virtualSales,
        goodsItems: goods_arr,
        goodSpec: good_spec,
        quotaNum: formData.quotaNum,
        goodSort: formData.sort,
        videoId: formData.videoId,
      };

      console.log("提交数据:", formJson.value);

      if (formData.id!='') {
        GoodsAPI.update(formJson.value)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        GoodsAPI.create(formJson.value)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 删除
function handleDelete(Id?: number) {
  const Ids = [Id || selectIds.value].join(",");

  if (!Ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      const id_json = {
        dataId: Ids,
      }
      GoodsAPI.deleteByIds(id_json)
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 重置表单
function resetForm() {
  FormRef.value.resetFields();
  FormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
  formData.sort = 1;
  formData.images = [];
  formData.content = ''
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  loadings.value = false
  resetForm();
}






onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.product-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.specification-section {
  border: 1px solid #eee;
  padding: 15px;
  border-radius: 4px;
}

.single-spec {
  display: flex;
  gap: 20px;
  margin-top: 15px;
}
</style>
